<?php

namespace iBrand\Shop\Core\Repositories;

use Prettus\Repository\Eloquent\BaseRepository;
use iBrand\Shop\Core\Models\Order;
use iBrand\Server\Models\OfflineOrder;
use Carbon\Carbon;

class OrderRepository extends BaseRepository
{
    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return Order::class;
    }

    /**
     * 根据订单编号获得订单数据
     *
     * @param $no
     *
     * @return mixed
     */
    public function getOrderByNo($no)
    {
        return $this->with(['items', 'user'])->findByField('order_no', $no)->first();
    }

    public function getShopOrderByNo($no)
    {
        return $this->with(['items', 'shippings', 'invoices', 'user', 'user.card', 'shopOrder.clerk'])->findByField('order_no', $no)->first();
    }

    public function getOrderOffilineByNo($no)
    {
        return OfflineOrder::with('goods')->where('order_no', $no)->first();
    }

    /**
     * 根据状态查询订单数据
     *
     * @param $input
     * @param $user_id
     *
     * @return mixed
     */
    public function getOrderByStatus($input, $user_id)
    {

        $order = $this->orderBy('created_at', 'desc')->with('items')->scopeQuery(function ($query) use ($input, $user_id) {
            $query = $query->where(['user_id' => $user_id]);
            if (isset($input['status']) && $input['status'] != 0) {
                $query->where(['status' => $input['status']]);
            } else {
                $query->where('status', '>', 0);
            }
            if (isset($input['type'])) {
                $query->where(['type' => $input['type']]);
            }

            return $query;
        })->paginate(15);

        return $order;
    }

    public function getOrdersByConditions($orderConditions, $itemConditions, $limit = 15, $withs = ['items'], $type = [0, 1], $clerk_id, $mobile, $is_clerk_owner = 0, $between)
    {

        $this->applyConditions($orderConditions);
        foreach ($withs as $with) {
            $this->with($with);
        }

        return $this->orderBy('created_at', 'desc')->scopeQuery(function ($query) use ($itemConditions, $type, $between) {
            if (is_array($type)) {
                $query = $query->whereIn('type', $type);
            } else {
                $query = $query->where('type', $type);
            }
            if (count($itemConditions) > 0) {
                $query = $query->whereHas('items', function ($query) use ($itemConditions) {
                    foreach ($itemConditions as $field => $value) {
                        if (is_array($value)) {
                            list($field, $condition, $val) = $value;
                            $query = $query->where($field, $condition, $val);
                        } else {
                            $query = $query->where($field, '=', $value);
                        }
                    }

                    //	return $query;
                });
            }

            if (count($between) > 0) {
                $query = $query->whereBetween('created_at', $between);
            }

            return $query;
        })
            ->with('user')
            ->whereHas('user', function ($query) use ($mobile) {
                if (!empty($mobile)) {
                    return $query->where('mobile', $mobile);
                } else {
                    return $query;
                }
            })
            ->with('shopOrder.clerk')
            ->whereHas('shopOrder', function ($query) use ($clerk_id, $is_clerk_owner) {
                if (!$is_clerk_owner) {
                    return $query->where('clerk_id', $clerk_id);
                }
            })->paginate($limit);
    }

    public function getOrdersByCriteria($andConditions, $orConditions, $limit = 15, $type = [0, 1], $clerk_id, $mobile, $is_clerk_owner = 0)
    {
        //线上订单
        $orderItemTable = 'el_order_item';
        $query = $this->model->join($orderItemTable, $this->model->getQualifiedKeyName(), '=', $orderItemTable . '.order_id');

        if (is_array($type)) {
            $query = $query->whereIn($this->model->getTable() . '.' . 'type', $type);
        } else {
            $query = $query->where($this->model->getTable() . '.' . 'type', $type);
        }

        foreach ($andConditions as $field => $value) {
            if (is_array($value)) {
                list($field, $condition, $val) = $value;
                $query = $query->where($this->model->getTable() . '.' . $field, $condition, $val);
            } else {
                $query = $query->where($this->model->getTable() . '.' . $field, '=', $value);
            }
        }

        $ids = $query->where(function ($query) use ($orConditions) {
            $index = 1;
            foreach ($orConditions as $field => $value) {
                if (is_array($value)) {
                    list($field, $condition, $val) = $value;
                    if ($index == 1) {
                        $query = $query->where($field, $condition, $val);
                    } else {
                        $query = $query->orWhere($field, $condition, $val);
                    }
                } else {
                    if ($index == 1) {
                        $query = $query->where($field, '=', $value);
                    } else {
                        $query = $query->orWhere($field, '=', $value);
                    }
                }
                $index++;
            }
        })->select($this->model->getTable() . '.*')->get()->pluck('id');

        return $this->orderBy('created_at', 'desc')->with('items')->scopeQuery(function ($query) use ($ids) {
            return $query->whereIn('id', $ids);
        })
            ->with('user')
            ->whereHas('user', function ($query) use ($mobile) {
                if (!empty($mobile)) {
                    return $query->where('mobile', $mobile);
                } else {
                    return $query;
                }
            })
            ->with('shopOrder.clerk')
            ->whereHas('shopOrder', function ($query) use ($clerk_id, $is_clerk_owner) {
                if (!$is_clerk_owner) {
                    return $query->where('clerk_id', $clerk_id);
                }
            })
            ->paginate($limit);
    }

    /**
     * 根据状态和用户获取订单的数量
     *
     * @param $user_id
     * @param $status
     *
     * @return mixed
     */
    public function getOrderCountByUserAndStatus($user_id, $status)
    {

        return $this->model->where('user_id', $user_id)->where('status', $status)->count();
    }

    /**
     * 统计店员当日销售总额
     *
     * @param $clerk_id
     * @param $shop_id
     *
     * @return int
     */
    public function getOrderTotalCountTodayByClerkID($clerk_id, $shop_id)
    {
        $today = Carbon::today()->timestamp;
        $tomorrow = Carbon::tomorrow()->timestamp;

        $value = $this->model->where('channel', 'shop')
            ->where('channel_id', $shop_id)
            ->whereIn('status', [Order::STATUS_RECEIVED, Order::STATUS_COMPLETE])
            ->with('shopOrder')
            ->whereHas('shopOrder', function ($query) use ($clerk_id, $tomorrow, $today) {
                return $query->where('clerk_id', $clerk_id)
                    ->where('created_at', '>=', Carbon::createFromTimestamp($today));
                /*->where('created_at', '<', Carbon::createFromTimestamp($tomorrow));*/
            })->sum('total');

        if ($value == null) {
            return 0;
        }

        return number_format($value / 100, 2, ".", "");
    }

    /**
     * 统计店员近N天销售总额
     *
     * @param $clerk_id
     * @param $day
     * @param $shop_id
     *
     * @return int
     */
    public function getOrderTotalCountDayByClerkID($clerk_id, $day, $shop_id)
    {
        $today = Carbon::today()->timestamp;

        $tomorrow = Carbon::tomorrow()->timestamp;

        $value = $this->model->where('channel', 'shop')
            ->where('channel_id', $shop_id)
            ->whereIn('status', [Order::STATUS_RECEIVED, Order::STATUS_COMPLETE])
            ->with('shopOrder')
            ->whereHas('shopOrder', function ($query) use ($clerk_id, $tomorrow, $today, $day) {
                return $query->where('clerk_id', $clerk_id)
                    ->where('created_at', '>=', Carbon::createFromTimestamp(strtotime("$day day", $today)))
                    ->where('created_at', '<', Carbon::createFromTimestamp($tomorrow));
            })->sum('total');

        if ($value == null) {
            return 0;
        }

        return number_format($value / 100, 2, ".", "");
    }

    /**
     * 获取本店到目前为止本月的订单总金额
     *
     * @param      $clerk_id
     * @param bool $owner
     * @param      $shop_id
     *
     * @return int
     */
    public function getOrderTotalMonthByClerkIDorShopID($clerk_id, $owner = false, $shop_id)
    {

        $today = Carbon::today()->timestamp;

        $key = date('Y-m', $today);

        $value = $this->model->where('channel', 'shop')
            ->where('channel_id', $shop_id)
            ->whereIn('status', [Order::STATUS_RECEIVED, Order::STATUS_COMPLETE])
            ->with('shopOrder')
            ->whereHas('shopOrder', function ($query) use ($clerk_id, $key, $owner) {
                if ($owner) {
                    return $query->where('created_at', 'like', '%' . $key . '%');
                } else {
                    return $query->where('clerk_id', $clerk_id)->where('created_at', 'like', '%' . $key . '%');
                }
            })
            ->sum('total');

        if ($value == null) {
            return 0;
        }

        return number_format($value / 100, 2, ".", "");
    }

    /**
     * 获取本店到目前为止订单总数
     *
     * @param      $clerk_id
     * @param bool $owner
     * @param      $shop_id
     *
     * @return mixed
     */
    public function getOrderCountMonthByClerkIDorShopID($clerk_id, $owner = false, $shop_id)
    {
        $today = Carbon::today()->timestamp;

        $key = date('Y-m', $today);

        return $this->model->where('channel', 'shop')
            ->where('channel_id', $shop_id)
            ->whereIn('status', [Order::STATUS_RECEIVED, Order::STATUS_COMPLETE])
            ->with('shopOrder')
            ->whereHas('shopOrder', function ($query) use ($clerk_id, $key, $owner) {
                if (!$owner) {
                    return $query->where('clerk_id', $clerk_id)->where('created_at', 'like', '%' . $key . '%');
                } else {
                    return $query->where('created_at', 'like', '%' . $key . '%');
                }
            })->count();
    }

    /**
     * 根据用户ID获取用户的门店订单
     *
     * @param     $user_id
     * @param int $limit
     * @param int $shop_id
     *
     * @return mixed
     */
    public function getOrderByUserID($user_id, $limit = 15, $shop_id = 0)
    {
        return $this->where('user_id', $user_id)->orderBy('created_at', 'desc')->scopeQuery(function ($query) use ($shop_id) {
            $query->whereHas('shopOrder', function ($query) use ($shop_id) {
                if ($shop_id) {
                    return $query->where('shop_id', $shop_id);
                }
            });
        })->paginate($limit);
    }
}
